package blockchain

import (
	"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
	"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
	"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)

var (
	SDK				*fabsdk.FabricSDK
	ChannelName		= "mychannel"
	ChaincodeName	= "mycc"
	Org				= "org1"
	User			= "Admin"
	ConfigPath		= "/home/work/go/src/financial/deploy/config.yaml"
	TargetEndPoint1 = "node2.organization1.financial.cn"
	TargetEndPoint2 = "node2.organization2.financial.cn"
	TargetEndPoint3 = "node2.organization3.financial.cn"
)

// 初始化
func Init()  {
	var err error
	SDK, err =  fabsdk.New(config.FromFile(ConfigPath))
	if err != nil {
		panic(err)
	}
}

// 交互
func ChannelExecute(fcn string, args [][]byte) (channel.Response, error) {
	// 创建客户端
	ctx := SDK.ChannelContext(ChannelName, fabsdk.WithOrg(Org), fabsdk.WithUser(User))
	cli, err := channel.New(ctx)
	if err != nil {
		return channel.Response{}, err
	}
	resp, err := cli.Execute(channel.Request{
		ChaincodeID:     ChaincodeName,
		Fcn:             fcn,
		Args:            args,
	}, channel.WithTargetEndpoints(TargetEndPoint1, TargetEndPoint2, TargetEndPoint3))

	if err != nil {
		return channel.Response{}, err
	}
	return resp, nil
}

// 查询
func ChannelQuery(fcn string, args [][]byte) (channel.Response, error) {
	//创建客户端
	ctx := SDK.ChannelContext(ChannelName, fabsdk.WithOrg(Org), fabsdk.WithUser(User))
	cli, err := channel.New(ctx)
	if err != nil {
		return channel.Response{}, err
	}
	return cli.Query(channel.Request{
		ChaincodeID:     ChaincodeName,
		Fcn:             fcn,
		Args:            args,
	}, channel.WithTargetEndpoints(TargetEndPoint1, TargetEndPoint2, TargetEndPoint3))
}